package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.liaoye.hellocustomview.R;

/**
 * 线性渐变
 */
public class LinearGradientView extends View {

    private Paint mPaint;
    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;

    public LinearGradientView(Context context) {
        super(context);
        init();
    }

    public LinearGradientView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LinearGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        //设置画笔的基本属性
        mPaint = new Paint();

        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator);
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        LinearGradient linearGradient = new LinearGradient(0, getHeight() / 2, getWidth(), getHeight() / 2, 0xffff0000, 0xff00ff00, Shader.TileMode.CLAMP);

        LinearGradient linearGradient = new LinearGradient(0, getHeight() / 2, getWidth(), getHeight() / 2, new int[]{0xffff0000, 0xff00ff00, 0xff0000ff}, new float[]{0f, 0.5f, 1f}, Shader.TileMode.CLAMP);

        mPaint.setShader(linearGradient);

        canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), mPaint);


    }
}
